home *** CD-ROM | disk | FTP | other *** search
/ Language/OS - Multiplatform Resource Library / LANGUAGE OS.iso / cpp_libs / nihcl-30.lha / nihcl-3.0 / ex / ex11-3.c < prev    next >
C/C++ Source or Header  |  1990-05-15  |  2KB  |  71 lines

  1. // ex11-3.c -- Protecting a critical section of code
  2. //             with an AutoSignal
  3.  
  4. // $Header: /afs/alw.nih.gov/unix/sun4_40c/usr/local/src/nihcl-3.0/share/ex/RCS/ex11-3.c,v 3.0 90/05/15 22:44:25 kgorlen Rel $
  5.  
  6. #define BASE StackProc
  7. #if BASE == StackProc
  8. #include "StackProc.h"
  9. #endif
  10. #if BASE == HeapProc
  11. #include "HeapProc.h"
  12. #endif
  13.  
  14. #include "Scheduler.h"
  15. #include "Semaphore.h"
  16. #include "String.h"
  17.  
  18. static Semaphore protect_critical(1);
  19.  
  20. class AutoSignal {
  21.     Semaphore* as;
  22. public:
  23.     AutoSignal(Semaphore& s) { as= &s; as->wait(); }
  24.     ~AutoSignal() { as->signal(); }
  25. };
  26.  
  27. class TestProcess : public BASE {
  28. public:
  29.     TestProcess(const char* name, stackTy* bot, int pri);
  30.     static TestProcess* create(const char* name, int pri);
  31. };
  32.  
  33. TestProcess::TestProcess(const char* pname,stackTy* bot,int pri)
  34.             : BASE(pname,bot,pri)
  35. {
  36.     // parent process yields to allow this process to start
  37.     if ( FORK() ) { Scheduler::yield(); return; }
  38.  
  39.     while (1) {
  40.         // this block represents a critical section
  41.         // although it does nothing critical
  42.         AutoSignal autosig(protect_critical);
  43.         cout << name() << pri << " enter critical section" << endl;
  44.         break;
  45.         }
  46.  
  47.     // terminate to avoid return
  48.     terminate();
  49. }
  50.  
  51. TestProcess* TestProcess::create(const char* name, int pri)
  52. {
  53.     // the next two statements must be in the same scope
  54.     // for the address of the stack bottom to be correct
  55.     auto stackTy bottom;
  56.     return new TestProcess(name,&bottom,pri);
  57. }
  58.  
  59. main()
  60. {
  61.     // start Scheduler
  62.     // create main context with priority 0
  63.     MAIN_PROCESS(0);
  64.  
  65.     String* pname = new String("P"); 
  66.     for (register int i=MAXPRIORITY; i>=1; i--)
  67.         TestProcess::create(*pname,i);
  68.  
  69.     cout << "main Process" << endl;
  70. }
  71.